<?php

$page = "signin";
require 'require.php';


if (isset($_SESSION['user_id']) && ($_SESSION['user_id']) && isset($_SESSION['openid_mode']) && (($_SESSION['openid_mode'] == 'checkid_setup') or ($_SESSION['openid_mode'] == 'checkid_immediate'))) {
	header("Location: trust.php");
	exit;
} elseif (isset($_SESSION['user_id']) && ($_SESSION['user_id'])) {
	header("Location: index.php");
	exit;
}

if (isset($_POST['ois_action']) && ($_POST['ois_action'] == 'signin')) {

	if ( ((isset($_POST['ois_username']) && $_POST['ois_username']) || (isset($_SESSION['openid_identity']) && $_SESSION['openid_identity']))  && isset($_POST['ois_password']) && ($_POST['ois_password'])) {
	
		if (isset($_SESSION['openid_identity']))
			$_POST['ois_username']=substr($_SESSION['openid_identity'],20); // pour la prod 20; pour le dev 34		
		
		$link_server = mysql_connect(OPENIDOO_DB_SERVER, OPENIDOO_DB_USER, OPENIDOO_DB_PASSWORD);
		$select_db = mysql_select_db(OPENIDOO_DB_DATABASE, $link_server);

		if ((!$link_server) or (!$select_db)) {
			die('Impossible de se connecter');
		} else {
		
			if (!($signin = mysql_query("SELECT user_id, username, password FROM openidoo_accounts WHERE username='".mysql_escape_string($_POST['ois_username'])."' LIMIT 1", $link_server))) {
				die('Une erreur est survenue');
			} else {
				if (mysql_num_rows($signin) != 0) {

					$result = mysql_fetch_object($signin);
					if (isset($result->password) && ($result->password === $_POST['ois_password'])) {

						$_SESSION['user_id'] = $result->user_id;
						$_SESSION['username'] = $result->username;
						$_SESSION['password'] = $result->password;

						new_log('Sign In');

						if (isset($_SESSION['openid_mode']) && (($_SESSION['openid_mode'] == 'checkid_setup') or ($_SESSION['openid_mode'] == 'checkid_immediate'))) {
							header("Location: trust.php");
							exit;
						} else {
							header("Location: index.php");
							exit;
						}

					} else {
						$error = 'Password failed';
					}

				} else {
					$error = 'Unknown username';
				}

			}
		}

	}
}

require "html/top.html";
require "html/signin.html";
require "html/bottom.html";

?>
